package cn.aishua.ui.myKaka;

import org.apache.http.HttpResponse;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.aishua.R;
import cn.aishua.network.HttpRequestUtil;
import cn.aishua.ui.MainActivityGroup;
import cn.aishua.ui.myKaka.task.DataExchangeAsyncTask;
import cn.aishua.util.SharedPrefConst;

public class LoginActivity
    extends Activity
{
    // page header widgets
    private ImageView ivLeftBtn;
    private ImageView ivRightBtn;
    private TextView tvTitile;

    private SharedPreferences sharedPref;

    public final static String EXTRA_MSG_USER_NAME = "cn.aishua.ui.myKaka.userName";
    public final static String EXTRA_MSG_MOBILE_NUMBER = "cn.aishua.ui.myKaka.mobileNumber";
    public final static String EXTRA_MSG_MY_CREDIT = "cn.aishua.ui.myKaka.myCredit";
    public final static String EXTRA_MSG_MY_BANK_CARD = "cn.aishua.ui.myKaka.myBankCard";

    // shared preferences

    private EditText etUserName;
    private EditText etPwd;
    private CheckBox cbRememberAccount;
    private CheckBox cbAutoLogin;

    @Override
    public void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        //        llMain.addView( createView( R.layout.my_kaka_login, llMain ) );
        setContentView( R.layout.my_kaka_login );
        initPageHeader();
        //        llMenu = (LinearLayout) findViewById( R.id.slide_menu );
        //        llMain = (LinearLayout) findViewById( R.id.main_content );
        //        WIDTH = llMenu.getLayoutParams().width;
        //
        //        AddItemsIntoMenu();

        //        addContentView( llMain, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
        //        //        setContentView( R.layout.my_kaka_login );
        initiate();
    }

    private void initPageHeader()
    {
        // left button
        ivLeftBtn = (ImageView) findViewById( R.id.page_header_iv_left_btn );
        ivLeftBtn.setImageResource( R.drawable.btn_nav_header );
        ivLeftBtn.setOnClickListener( new OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                navigationBar();
            }
        } );

        // title
        tvTitile = (TextView) findViewById( R.id.page_header_tv_title );
        tvTitile.setText( "会员登录" );

        // right button
        ivRightBtn = (ImageView) findViewById( R.id.page_header_iv_right_btn );
        ivRightBtn.setVisibility( View.GONE );
    }

    private void initiate()
    {
        etUserName = (EditText) findViewById( R.id.my_kaka_login_et_user_name );
        etPwd = (EditText) findViewById( R.id.my_kaka_login_et_pwd );
        cbRememberAccount = (CheckBox) findViewById( R.id.my_kaka_login_cb_remember_account );
        cbAutoLogin = (CheckBox) findViewById( R.id.my_kaka_login_cb_auto_login );

        sharedPref = getSharedPreferences( "userInfo", Context.MODE_PRIVATE );
        Editor editor = sharedPref.edit();
        editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_USER_IS_LOGIN, false );
        editor.commit();

        if( sharedPref.getBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_CHECKED, false ) )
        {
            etUserName.setText( sharedPref.getString( SharedPrefConst.SHARED_PREF_STR_USER_NAME, "" ) );
            etPwd.setText( sharedPref.getString( SharedPrefConst.SHARED_PREF_STR_PWD, "" ) );
            cbAutoLogin.setChecked( true );
            cbRememberAccount.setChecked( true );
            if( !sharedPref.getBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_NOT_NEEDED, false ) )
            {
                login( null );
            }
        }
        else if( sharedPref.getBoolean( SharedPrefConst.SHARED_PREF_BOOL_REMEMBER_IS_CHECKED, false ) )
        {
            etUserName.setText( sharedPref.getString( SharedPrefConst.SHARED_PREF_STR_USER_NAME, "" ) );
            cbRememberAccount.setChecked( true );
        }
    }

    public void navigationBar()
    {
        MainActivityGroup parent = (MainActivityGroup) getParent();
        parent.handleNaviBar();
    }

    /**
     * Handle the click action on register button
     * 
     * @param view
     */
    public void register( View view )
    {

        Intent toRegisterPage = new Intent( this, RegisterActivity.class );

        startActivity( toRegisterPage );

    }

    public void checkAutoLogin( View view )
    {
        if( cbAutoLogin.isChecked() )
        {
            cbRememberAccount.setChecked( true );
        }
    }

    public void login( View view )
    {

        // get mobile number
        String userName = etUserName.getText().toString().trim();

        String pwd = etPwd.getText().toString().trim();

        if( !validateUserInfo( userName, pwd ) )
            return;

        handleLogin( userName, pwd );
    }

    private void handleLogin( String mobileNumber, String pwd )
    {

        new DataExchangeAsyncTask( this, "用户登陆" )
        {

            @Override
            protected HttpResponse sendRequest( String... params )
            {
                return HttpRequestUtil.getInstance().login( params );
            }

            @Override
            protected void handleSuccResponse( String strJson )
            {

                LoginActivity.this.handleSharedPref();

                MainActivityGroup parent = (MainActivityGroup) LoginActivity.this.getParent();
                parent.updateUserInfo();
                parent.ignoreNaviBar = true;
                parent.llLogin.performClick();
                //                Intent intent = new Intent( LoginActivity.this, MainActivity.class );
                //                intent.putExtra( MainActivity.TAB, MainActivity.TAG_USER_INFO );
                //                LoginActivity.this.startActivity( intent );

            }
        }.execute( mobileNumber, pwd );

    }

    /**
     * 1. For check boxes (remember account and auto login) 2. set USER_IS_LOGIN as true, store
     * session id from http response
     */
    private void handleSharedPref()
    {
        Editor editor = sharedPref.edit();

        // 1. auto login is checked
        if( cbAutoLogin.isChecked() )
        {
            String userName = etUserName.getText().toString().trim();
            String pwd = etPwd.getText().toString().trim();

            editor.putString( SharedPrefConst.SHARED_PREF_STR_USER_NAME, userName );
            editor.putString( SharedPrefConst.SHARED_PREF_STR_PWD, pwd );
            editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_CHECKED, true );
            editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_REMEMBER_IS_CHECKED, true );
        }
        else
        // 2. auto login is unchecked
        {
            editor.remove( SharedPrefConst.SHARED_PREF_STR_USER_NAME );
            editor.remove( SharedPrefConst.SHARED_PREF_STR_PWD );
            editor.remove( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_CHECKED );

            // handle remember account function
            if( cbRememberAccount.isChecked() )
            {
                String userName = LoginActivity.this.etUserName.getText().toString().trim();
                editor.putString( SharedPrefConst.SHARED_PREF_STR_USER_NAME, userName );
                editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_REMEMBER_IS_CHECKED, true );

            }
            else
            {
                editor.remove( SharedPrefConst.SHARED_PREF_STR_USER_NAME );
                editor.remove( SharedPrefConst.SHARED_PREF_BOOL_REMEMBER_IS_CHECKED );
            }
        }

        editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_USER_IS_LOGIN, true );
        editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_NOT_NEEDED, false );
        editor.commit();
    }

    /**
     * validate input mobile number and password
     */
    private boolean validateUserInfo( String mobileNumber, String pwd )
    {

        if( mobileNumber == null || "".equals( mobileNumber ) )
        {
            Toast.makeText( this, R.string.input_valid_mobile_number, Toast.LENGTH_SHORT ).show();
            return false;
        }

        if( pwd == null || "".equals( pwd ) )
        {
            Toast.makeText( this, R.string.input_valid_pwd, Toast.LENGTH_SHORT ).show();
            return false;
        }

        return true;
    }
}
